package com.java110.mall.goods.cmd.goodsClass;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.goodsClass.GoodsClassDto;
import com.java110.intf.goods.IGoodsClassV1InnerServiceSMO;
import com.java110.utils.exception.CmdException;
import com.java110.vo.ResultVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Java110Cmd(serviceCode = "goodsClass.listGoodsClassesTree")
public class ListGoodsClassTreeCmd extends Cmd {

    @Autowired
    private IGoodsClassV1InnerServiceSMO goodsClassV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        GoodsClassDto goodsClassDto = new GoodsClassDto();
        goodsClassDto.setIsOutside("0");
        List<GoodsClassDto> goodsClassDtos = goodsClassV1InnerServiceSMOImpl.queryGoodsClasss(goodsClassDto);
        List<GoodsClassDto> goodsClassDtoTree = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(goodsClassDtos)) {
            for (GoodsClassDto goodsClass : goodsClassDtos) {
                goodsClass.setText(goodsClass.getClassName());
                if (GoodsClassDto.TOP_LEVEL_PID.equals(goodsClass.getClassPid())){
                    findChild(goodsClassDtos, goodsClass);
                    goodsClassDtoTree.add(goodsClass);
                }
            }
        }
        if (!ObjectUtils.isEmpty(reqJson.get("classId"))) {
            goodsClassDtoTree.clear();
            goodsClassDto.setClassId(reqJson.get("classId").toString());
            List<GoodsClassDto> goodsClassDtoList = goodsClassV1InnerServiceSMOImpl.queryGoodsClasss(goodsClassDto);
            findChild(goodsClassDtos, goodsClassDtoList.get(0));
            goodsClassDtoTree.add(goodsClassDtoList.get(0));
        }

        cmdDataFlowContext.setResponseEntity(ResultVo.createResponseEntity(goodsClassDtoTree));
    }

    private void findChild(List<GoodsClassDto> goodsClassDtos, GoodsClassDto goodsClass) {
        List<GoodsClassDto> childs = new ArrayList<>();
        for (GoodsClassDto goodsClassDto : goodsClassDtos) {
            if (goodsClassDto.getClassPid().equals(goodsClass.getClassId())) {//二级
                childs.add(goodsClassDto);
            }
        }

        if (childs.size() < 1) {
            return;
        }

        goodsClass.setChildren(childs);

        for (GoodsClassDto goodsClassDto : childs) {
            findChild(goodsClassDtos, goodsClassDto);
        }
    }
}
